package com.jemmyee.pizza.web.controller;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.jemmyee.core.dao.Page;
import com.jemmyee.core.utils.DateUtils;
import com.jemmyee.pizza.entity.Excerpt;
import com.jemmyee.pizza.entity.Surrogate;
import com.jemmyee.pizza.entity.SurrogateCCB;
import com.jemmyee.pizza.service.IExcerptService;
import com.jemmyee.pizza.service.ISurrogateCCBService;
import com.jemmyee.pizza.web.Constants;
import com.jemmyee.pizza.web.bean.SurrogateBean;

@Controller
@RequestMapping("/admin/surrogateCCB")
public class SurrogateCCBController {
	@Autowired
	private ISurrogateCCBService surrogateCCBService;
	
	@Autowired
	private IExcerptService excerptService;

	@RequestMapping("/list/{from}/{startIndex}")
	public ModelAndView list(@PathVariable Integer startIndex,
			@PathVariable String from, @ModelAttribute SurrogateBean bean,
			HttpServletRequest request) {
		DetachedCriteria dc = DetachedCriteria.forClass(SurrogateCCB.class);
		SurrogateBean surrogateBean = new SurrogateBean();
		if (from.equals("form")) {
			surrogateBean = bean;
			request.getSession().setAttribute(Constants.SESSION_PAGE_SYS_QUERY_BEAN, surrogateBean);
		}
		if (from.equals("page")) {
			if (request.getSession().getAttribute(Constants.SESSION_PAGE_SYS_QUERY_BEAN) != null) {
				surrogateBean = (SurrogateBean) request.getSession().getAttribute(Constants.SESSION_PAGE_SYS_QUERY_BEAN);
			}
		}
		if (from.equals("menu")) {
			System.out.println("menu is call");
		}
		
		
		
		//查询条件
		if(surrogateBean.getName() != null){
			dc.add(Restrictions.like("payPerson", surrogateBean.getName(), MatchMode.ANYWHERE));
		}
		// 发布时间
		if (surrogateBean.getStartTime() != null) {
			dc.add(Restrictions.ge("importTime", surrogateBean.getStartTime()));
		}
		if (surrogateBean.getEndTime() != null) {
			dc.add(Restrictions.le("importTime", surrogateBean.getEndTime()));
		}
		
		
		Page page = surrogateCCBService.findPageByCriteria(dc,
				Constants.DEFAULT_PAGESIZE, startIndex, "payPerson");

		ModelAndView mv = new ModelAndView();
		mv.addObject("page", page);
		mv.setViewName("/admin/surrogateCCB/list");
		return mv;
	}

	@RequestMapping("/to_up_txt")
	public ModelAndView toUpTxt() {
		ModelAndView mv = new ModelAndView();
		mv.setViewName("/admin/surrogateCCB/up_txt");
		return mv;
	}

	
	@RequestMapping("/up_txt")
	public ModelAndView upTxt(HttpServletRequest request) throws IOException {
		ModelAndView mv = new ModelAndView();
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		CommonsMultipartFile cmf = (CommonsMultipartFile) multipartRequest
				.getFile("txtFile");
		if (!cmf.getOriginalFilename().substring(
				cmf.getOriginalFilename().lastIndexOf(".") + 1).equals("txt")) {
			System.out.println("文件类型错误");
			mv.addObject("message", "文件类型错误");
			mv.setViewName("/admin/surrogateCCB/up_txt");
			return mv;
		}
		try {
			readTxtToTable(cmf.getInputStream(),request.getParameter("time"));
			mv.setViewName("/admin/surrogateCCB/up_txt");
		} catch (IOException e) {
			mv.addObject("message", "文件上传错误");
			e.printStackTrace();
			mv.setViewName("/admin/surrogateCCB/up_txt");
		}
		
		return mv;
	}
	
	/**
	 * 将txt格式文件写入数据库
	 * @param ins 文件字节流
	 * @param time 操作时间（可选）
	 * @throws IOException
	 */
	private void readTxtToTable(InputStream ins,String time) throws IOException{
		SimpleDateFormat format = new SimpleDateFormat(DateUtils.DATE_FORMAT_YYMMDDHHMMSS);
		DataInputStream in = new DataInputStream(ins);
		BufferedReader bufferedreader =  new BufferedReader(new InputStreamReader(in,"GBK"));
		String stemp;   
		while((stemp = bufferedreader.readLine()) != null){
			//读取一行
			String[]s=  stemp.split("\\|");
			SurrogateCCB sc=new SurrogateCCB();
			sc.setBankNo(s[0]);
			sc.setCardNo(s[1]);
			sc.setPayPerson(s[2]);
			sc.setPayMoney(Double.valueOf(s[3]));
			sc.setPayType(s[4]);
			sc.setPayState(s[10]);//索引5到9为空字符
			sc.setImportTime(format.format(new Date()));
			surrogateCCBService.save(sc);
			
			
			
			if(sc.getPayState().equals("成功")){
				DetachedCriteria dc = DetachedCriteria.forClass(Excerpt.class);
				dc.add(Restrictions.eq("personCard", sc.getCardNo()));
				dc.add(Restrictions.eq("personName", sc.getPayPerson()));
				dc.add(Restrictions.eq("substr(excerptTime,1,7)", time));
				List<Excerpt> lt_1 = excerptService.findByCriteria(dc);
				if(lt_1 != null && lt_1.size() == 1){
					Excerpt excerpt = new Excerpt();
					excerpt = lt_1.get(0);
					excerpt.setPayStatus(1);
					excerptService.update(excerpt);
				}
			}
			
		}
		
	}
}
